package com.apes.framework.plugin.esb.processor;

import com.apes.framework.plugin.esb.api.Request;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.rop.session.SimpleSession;
import com.apes.framework.util.EventUtil;
import com.apes.framework.util.MapUtil;
import com.apes.framework.util.Tools;

import java.util.Map;

/**
 * 功能：流程处理器
 *
 * @author xul
 * @create 2018-06-26 11:31
 */
public class ProcessProcessor<T extends Request, R> extends AbstractChainProcessor<T, R> {

    private String id; //流程编号

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    @Override
    protected R doProcess(T source) {
        try {
            Map data;
            Object o = source.getData();
            if (o instanceof String) {
                data = source.getMap();
            } else {
                data = MapUtil.mapped(o);
            }
            SimpleSession session = (SimpleSession) ((SimpleRequest) source).getRopRequestContext().getSession();
            if (session != null &&
                    !(data.containsKey("processInitiator") && data.containsKey("processInitiatingDepartment") && data.containsKey("processInitiatingPost"))) {
                String processInitiator = session.getUserId(); //流程发起人
                data.put("processInitiator", processInitiator);
                String processInitiatingDepartment = session.getBranchId(); //流程发起部门
                data.put("processInitiatingDepartment", processInitiatingDepartment);
                String processInitiatingPost = session.getAttribute("workPostId", String.class); //流程发起岗位
                data.put("processInitiatingPost", processInitiatingPost);
            }

            if (!data.containsKey("processInitiator") || Tools.isNull(data.get("processInitiator"))) {
                throw new RuntimeException("流程发起人不允许为空！");
            }

            data.put("taskExecutor", data.get("processInitiator"));
            data.put("taskExecutorDepartment", data.get("processInitiatingDepartment"));
            data.put("taskExecutorPost", data.get("processInitiatingPost"));
            String topic = "event:wf.startProcessInstanceById";
            Map body = MapUtil.mapper("processDefinitionKey", this.id, "variables", data);
            String processInstanceId = (String) EventUtil.sendSynEvent(this, topic, body).stream().findFirst().get();
            data.put("processInstanceId", processInstanceId);
            return (R) o;
        } catch (Exception e) {
            throw e;
        }
    }
}
